package com.atqar.callanble;


import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

class MyThread implements Callable<Integer> {

    //callable和runnable的区别
    //是否有返回值是否抛出异常,方法不同

    @Override
    public Integer call() throws Exception
    {
        System.out.println("实现callable");
        //暂停几秒钟线程
        try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
        return 666;
    }
}

public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //thread没有callable的构造方法,找个("中间人来完成")futuretask,futuretask在可以用来在后台完成比较耗时的计算不阻塞主线程
        FutureTask futureTask = new FutureTask(new MyThread());
        Thread thread = new Thread(futureTask, "a");
        thread.start();


        //System.out.println(futureTask.get());
        FutureTask futureTask2 = new FutureTask(new MyThread());
        Thread thread2 = new Thread(futureTask2, "b");
        thread2.start();

        System.out.println(Thread.currentThread().getName());
        //get的方法放在最后或者会阻塞get下面的线程
        System.out.println(futureTask.get());
    }

}
